[LeetCode] 364. Nested List Weight Sum II 嵌套链表权重和之二

 

Given a nested list of integers, return the sum of all integers in the list weighted by their depth.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Different from the previous question where weight is increasing from root to leaf, now the weight is defined from bottom up. i.e., the leaf level integers have weight 1, and the root level integers have the largest weight.

Example 1:

Input: [[1,1],2,[1,1]]
Output: 8 
Explanation: Four 1's at depth 1, one 2 at depth 2.

Example 2:

Input: [1,[4,[6]]]
Output: 17 
Explanation: One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1; 1*3 + 4*2 + 6*1 = 17.

 

这道题是之前那道 Nested List Weight Sum 的拓展,与其不同的是,这里的深度越深,权重越小,和之前刚好相反。但是解题思路没有变,还可以用 DFS 来做,由于遍历的时候不知道最终的 depth 有多深,则不能遍历的时候就直接累加结果,博主最开始的想法是在遍历的过程中建立一个二维数组,把每层的数字都保存起来,然后最后知道了 depth 后,再来计算权重和,比如题目中给的两个例子,建立的二维数组分别为:

[[1,1],2,[1,1]]:

1 1 1 1
2

[1,[4,[6]]]:

1
4
6

这样我们就能算出权重和了,参见代码如下:

 

解法一:

class Solution {
public:
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        int res = 0;
        vector<vector<int>> all;
        for (auto &a : nestedList) {
            helper(a, 0, all);
        }
        for (int i = (int)all.size() - 1; i >= 0; --i) {
            for (int j = 0; j < all[i].size(); ++j) {
                res += all[i][j] * ((int)all.size() - i);
            }
        }
        return res;
    }
    void helper(NestedInteger& ni, int depth, vector<vector<int>>& all) {
        vector<int> t;
        if (depth < all.size()) t = all[depth];
        else all.push_back(t);
        if (ni.isInteger()) {
            t.push_back(ni.getInteger());
            all[depth] = t;
        } else {
            for (auto &a : ni.getList()) {
                helper(a, depth + 1, all);
            }
        }
    }
};

 

其实上面的方法可以简化,由于每一层的数字不用分别保存,每个数字分别乘以深度再相加,跟每层数字先相加起来再乘以深度是一样的,这样只需要一个一维数组就可以了,只要把各层的数字和保存起来,最后再计算权重和即可:

 

解法二:

class Solution {
public:
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        int res = 0;
        vector<int> v;
        for (auto &a : nestedList) {
            helper(a, 0, v);
        }
        for (int i = (int)v.size() - 1; i >= 0; --i) {
            res += v[i] * ((int)v.size() - i);
        }
        return res;
    }
    void helper(NestedInteger& ni, int depth, vector<int>& v) {
        if (depth >= v.size()) v.resize(depth + 1);
        if (ni.isInteger()) {
            v[depth] += ni.getInteger();
        } else {
            for (auto &a : ni.getList()) {
                helper(a, depth + 1, v);
            }
        }
    }
};

 

下面这个方法就比较巧妙了,由史蒂芬大神提出来的,核心思想是把每一层的数字都先加起来放到一个变量 unweighted 中,然后每层遍历完了之后,就加到 weighted 变量中。再遍历下一层,再把数字加到 unweighted 中,当前层遍历完成了之后再次加到 weighted 变量中,注意此时 unweighted 中还包含上一层的数字和,此时就相当于上一层的数字和加了两次,完美的符合题目的要求,若只有两层的话,第一层的深度是2,以此类推,越往里层遍历,外层的数字和就会继续被累加到 weighted 中,也就相当于数字和乘以深度了。

理解了题目思路,代码就比较好写了,定义两个变量 unweighted 和 weighted,非权重和跟权重和,初始化均为0,然后如果 nestedList 不为空开始循环,先声明一个空数组 nextLevel,遍历 nestedList 中的元素,如果是数字,则非权重和加上这个数字,如果是数组,就加入 nextLevel,这样遍历完成后,第一层的数字和保存在非权重和 unweighted 中了,其余元素都存入了 nextLevel 中,此时将 unweighted 加到 weighted 中,将 nextLevel 赋给 nestedList,这样再进入下一层计算,由于上一层的值还在 unweighted 中,所以第二层计算完将 unweighted 加入 weighted 中时,相当于第一层的数字和被加了两次,这样就完美的符合要求了,这个思路又巧妙又牛B,大神就是大神啊,参见代码如下:

 

解法三:

class Solution {
public:
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        int unweighted = 0, weighted = 0;
        while (!nestedList.empty()) {
            vector<NestedInteger> nextLevel;
            for (auto a : nestedList) {
                if (a.isInteger()) {
                    unweighted += a.getInteger();
                } else {
                    nextLevel.insert(nextLevel.end(), a.getList().begin(), a.getList().end());
                }
            }
            weighted += unweighted;
            nestedList = nextLevel;
        }
        return weighted;
    }
}; 

 

下面这种算法是常规的 BFS 解法,利用上面的建立两个变量 unweighted 和 weighted 的思路,大体上没什么区别:

 

解法四:

class Solution {
public:
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        int unweighted = 0, weighted = 0;
        queue<vector<NestedInteger>> q;
        q.push(nestedList);
        while (!q.empty()) {
            int size = q.size();
            for (int i = 0; i < size; ++i) {
                vector<NestedInteger> t = q.front(); q.pop();
                for (auto a : t) {
                    if (a.isInteger()) unweighted += a.getInteger();
                    else if (!a.getList().empty()) q.push(a.getList());
                }
            }
            weighted += unweighted;
        }
        return weighted;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/364

 

类似题目:

Nested List Weight Sum

Array Nesting

 

参考资料:

https://leetcode.com/problems/nested-list-weight-sum-ii/

https://leetcode.com/problems/nested-list-weight-sum-ii/discuss/83655/JAVA-AC-BFS-solution

https://leetcode.com/problems/nested-list-weight-sum-ii/discuss/83641/No-depth-variable-no-multiplication

https://leetcode.com/problems/nested-list-weight-sum-ii/discuss/114195/Java-one-pass-DFS-solution-mathematically

https://leetcode.com/problems/nested-list-weight-sum-ii/discuss/83649/Share-my-2ms-intuitive-one-pass-no-multiplication-solution

 

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2016-06-24 23:35  Grandyang  阅读(14526)  评论(10编辑  收藏  举报
Fork me on GitHub